﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;

using System.Web.UI;
using System.Threading;

namespace CNdotnet.Ezsocio.GadgetFramework
{
    public abstract class GadgetBase : UserControl, IGadgetContext
    {
        #region IGadgetBase Members

        public Guid GadgetID { get; set; }

        public string Title { get; set; }

        public bool IsShowTitle { get; set; }


        public StringDictionary GetSettings()
        {
            StringDictionary result = null;

            string id = "ez_gadget_" + GadgetID.ToString();
            if (Cache[id] == null)
            {
                GadgetSettings gs = new GadgetSettings(GadgetID);
                result = (StringDictionary)gs.GetSettings();
                Cache[id] = result;
            }

            return result;
        }

        public void SaveSettings(StringDictionary settings)
        {
        }

        #endregion

        #region Public members

        public abstract string Name { get; }

        public abstract bool IsEditable { get; }

        public abstract void LoadGadget();

        protected override void Render(HtmlTextWriter writer)
        {
            if (string.IsNullOrEmpty(Name))
            {
                throw new NullReferenceException();
            }

            StringBuilder sb = new StringBuilder();

            sb.Append("<div class=\"gadget " + this.Name.Replace(" ", string.Empty).ToLowerInvariant() + "\" id=\"gadget" + GadgetID.ToString() + " ");

            if (Thread.CurrentPrincipal.IsInRole("Administrators"))
            {
                sb.Append("<a class=\"delete\" href=\"javascript:void(0)\" onclick=\"removeGadget('" + GadgetID + "');return false\" title=\"Delete" + " gadget\">X</a>");
                if(IsEditable)
                {
                    sb.Append("<a class=\"edit\" href=\"javascript:void(0)\" onclick=\"editGadget('" + Name + "', '" + GadgetID + "');return false\" title=\"Edit" + " gadget\">" + "Edit" + "</a>");
                }
            }

            if(IsShowTitle)
            {
                sb.Append("<h3>" + Title + "</h3>");
            }
            else
            {
                sb.Append("<br />");
            }

            sb.Append("<div class=\"content\">");

            writer.Write(sb.ToString());
            base.Render(writer);
            writer.Write("</div>");
            writer.Write("</div>");
        }

        #endregion
    }
}
